package ru.papergames.web.blines.battle;

import ru.papergames.common.beans.BattleMember;
import ru.papergames.web.blines.battle.model.BattleOrder2;
import ru.papergames.web.cache.PlayersManager;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * TODO: add description
 * Date: 06.01.12 23:09
 *
 * @author Alexander Troshanin
 */
public class BattleOrdersHolder2 {

    private static BattleOrdersHolder2 instance = new BattleOrdersHolder2();

    //                              battleId battleOrder
    private final ConcurrentHashMap<Integer, BattleOrder2> battleOrdersMap = new ConcurrentHashMap<Integer, BattleOrder2>();

    public static BattleOrdersHolder2 getInstance() {
        return instance;
    }

    private BattleOrdersHolder2() {
    }

    public ConcurrentHashMap<Integer, BattleOrder2> getBattleOrdersMap() {
        return battleOrdersMap;
    }

    public void addOrdersAndLaunch(List<BattleOrder2> battleOrders) {
        for (BattleOrder2 battleOrder : battleOrders) {
            battleOrdersMap.put(battleOrder.getId(), battleOrder);
            launchBattleOrder(battleOrder);
        }
    }

    private void launchBattleOrder(BattleOrder2 battleOrder) {
        BattleServersManager.getInstance().createBattle(new BattleLifeCycleListenerImpl(battleOrder), battleOrder);
    }

    public void removeBattleOrder(BattleOrder2 battleOrder) {
        battleOrdersMap.remove(battleOrder.getId());
        for (BattleMember member : battleOrder.getPcMembers().values()) {
            PlayersManager.getInstance().removePlayersBattle(member.getId());
        }
    }
}
